<template>
  <el-main>
    <h3 v-if="!hospitalSet.id">添加医院设置</h3>
    <h3 v-if="hospitalSet.id">修改医院设置</h3>
    <el-form ref="form" :model="hospitalSet" label-width="100%">
      <el-form-item label="医院名称">
        <el-input v-model="hospitalSet.hosname"></el-input>
      </el-form-item>
      <el-form-item label="医院编号">
        <el-input v-model="hospitalSet.hoscode"></el-input>
      </el-form-item>
      <el-form-item label="api基础路径">
        <el-input v-model="hospitalSet.apiUrl"></el-input>
      </el-form-item>
      <el-form-item label="联系人姓名">
        <el-input v-model="hospitalSet.contactsName"></el-input>
      </el-form-item>
      <el-form-item label="联系人手机">
        <el-input v-model="hospitalSet.contactsPhone"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="saveOrUpdate">保存</el-button>
      </el-form-item>
    </el-form>
  </el-main>
</template>

<script>
// 引入接口
import hospSet from '../../api/hospset'
export default {
  name: 'add',
  data() {
    return {
      hospitalSet: {},
    }
  },
  created() {
    if (this.$route.params && this.$route.params.id) {
      const id = this.$route.params.id;
      this.getHospitalSetById(id);
      // alert(id)
    }
  },
  methods: {
    // 添加或更新医院设置
    saveOrUpdate() {
      if (this.hospitalSet.id) {
        // 更新操作
        this.update();
      } else {
        // 添加操作
        this.add();
      }
    },
    // 添加操作
    add() {
      hospSet.saveHospitalSet(this.hospitalSet).then(
        response => {
          // 提示
          this.$message({
            type: 'success',
            message: '医院设置添加成功！'
          });
          // 跳转到列表页面，使用路由
          this.$router.push({path: '/hospSet/list'});
        }
      ).catch(
        error => {
          // 提示
          this.$message({
            type: 'error',
            message: '添加失败!'
          });
        }
      )
    },
    // 修改操作
    update() {
      hospSet.updateHospitalSetById(this.hospitalSet).then(
        response => {
          // 提示
          this.$message({
            type: 'success',
            message: '医院设置修改成功！'
          });
          // 跳转到列表页面，使用路由
          this.$router.push({path: '/hospSet/list'});
        }
      ).catch(
        error => {
          // 提示
          this.$message({
            type: 'error',
            message: '修改失败!'
          });
        }
      )
    },
    // 通过 id 获取医院设置信息，并将数据展示在表单中
    getHospitalSetById(id) {
      hospSet.getHospitalSetById(id).then(
        response => {
          this.hospitalSet = response.data;
          // console.log(response.data)
        }
      ).catch(
        error => {
          // 提示
          this.$message({
            type: 'error',
            message: '获取医院信息失败!'
          });
        }
      )
    }
  }
}
</script>

<style scoped>
  div {
    width: 500px;
  }
</style>
